<template>
  <div class="after-sale">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="订单编号">
          <el-input v-model="searchForm.orderNo" placeholder="请输入订单编号" clearable />
        </el-form-item>
        <el-form-item label="售后类型">
          <el-select v-model="searchForm.type" placeholder="请选择类型" clearable>
            <el-option
              v-for="item in afterSaleTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="处理状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="申请时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 列表区域 -->
    <el-card class="list-card">
      <template #header>
        <div class="card-header">
          <span>售后列表</span>
          <el-radio-group v-model="viewType" size="small">
            <el-radio-button label="all">全部</el-radio-button>
            <el-radio-button label="pending">待处理</el-radio-button>
            <el-radio-button label="processing">处理中</el-radio-button>
            <el-radio-button label="completed">已完成</el-radio-button>
          </el-radio-group>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
      >
        <el-table-column prop="afterSaleNo" label="售后编号" width="180" />
        <el-table-column prop="orderNo" label="关联订单" width="180" />
        <el-table-column prop="type" label="售后类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTag(row.type)">
              {{ getTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="reason" label="申请原因" min-width="200" show-overflow-tooltip />
        <el-table-column prop="amount" label="退款金额" width="120">
          <template #default="{ row }">
            <span v-if="row.type === 'refund'" class="amount">¥ {{ row.amount }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="处理状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="申请时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleDetail(row)">详情</el-button>
            <el-button 
              v-if="row.status === 'pending'" 
              link 
              type="primary" 
              @click="handleProcess(row)"
            >
              处理
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 售后详情抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      :title="`售后详情 - ${currentRecord.afterSaleNo}`"
      size="50%"
      destroy-on-close
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="售后编号">{{ currentRecord.afterSaleNo }}</el-descriptions-item>
        <el-descriptions-item label="关联订单">{{ currentRecord.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ currentRecord.createTime }}</el-descriptions-item>
        <el-descriptions-item label="售后类型">
          <el-tag :type="getTypeTag(currentRecord.type)">
            {{ getTypeText(currentRecord.type) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="处理状态">
          <el-tag :type="getStatusTag(currentRecord.status)">
            {{ getStatusText(currentRecord.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="申请原因">{{ currentRecord.reason }}</el-descriptions-item>
        <el-descriptions-item label="退款金额" v-if="currentRecord.type === 'refund'">
          ¥ {{ currentRecord.amount }}
        </el-descriptions-item>
        <el-descriptions-item label="处理记录">
          <el-timeline>
            <el-timeline-item
              v-for="(record, index) in currentRecord.records"
              :key="index"
              :timestamp="record.time"
              :type="record.type"
            >
              {{ record.content }}
              <div class="operator">操作人：{{ record.operator }}</div>
            </el-timeline-item>
          </el-timeline>
        </el-descriptions-item>
      </el-descriptions>

      <!-- 处理表单 -->
      <template v-if="currentRecord.status === 'pending'">
        <el-divider>处理意见</el-divider>
        <el-form
          ref="processFormRef"
          :model="processForm"
          :rules="processRules"
          label-width="100px"
        >
          <el-form-item label="处理结果" prop="result">
            <el-radio-group v-model="processForm.result">
              <el-radio label="agree">同意</el-radio>
              <el-radio label="reject">拒绝</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="处理备注" prop="remark">
            <el-input
              v-model="processForm.remark"
              type="textarea"
              rows="3"
              placeholder="请输入处理备注"
            />
          </el-form-item>
        </el-form>
        <div class="drawer-footer">
          <el-button @click="drawerVisible = false">取消</el-button>
          <el-button type="primary" @click="submitProcess" :loading="submitting">
            确认处理
          </el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 处理弹窗 -->
    <el-dialog
      title="售后处理"
      v-model="dialogVisible"
      width="500px"
      @close="resetProcessForm"
    >
      <el-form
        ref="processFormRef"
        :model="processForm"
        :rules="processRules"
        label-width="100px"
      >
        <el-form-item label="处理结果" prop="result">
          <el-radio-group v-model="processForm.result">
            <el-radio label="agree">同意</el-radio>
            <el-radio label="reject">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="处理备注" prop="remark">
          <el-input
            v-model="processForm.remark"
            type="textarea"
            rows="3"
            placeholder="请输入处理备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitProcess" :loading="submitting">
          确认处理
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'

// 搜索表单
const searchForm = ref({
  orderNo: '',
  type: '',
  status: '',
  dateRange: []
})

// 表格相关
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const viewType = ref('all')

// 抽屉相关
const drawerVisible = ref(false)
const currentRecord = ref<any>({})

// 处理弹窗相关
const dialogVisible = ref(false)
const submitting = ref(false)
const processFormRef = ref<FormInstance>()
const processForm = ref({
  result: 'agree',
  remark: ''
})

const processRules = {
  result: [{ required: true, message: '请选择处理结果', trigger: 'change' }],
  remark: [{ required: true, message: '请输入处理备注', trigger: 'blur' }]
}

// 选项数据
const afterSaleTypes = [
  { value: 'refund', label: '退款' },
  { value: 'exchange', label: '换货' },
  { value: 'repair', label: '维修' }
]

const statusOptions = [
  { value: 'pending', label: '待处理' },
  { value: 'processing', label: '处理中' },
  { value: 'completed', label: '已完成' },
  { value: 'rejected', label: '已拒绝' }
]

// 模拟数据
const tableData = ref([
  {
    afterSaleNo: 'AS20231128001',
    orderNo: 'DD20231128001',
    type: 'refund',
    reason: '商品质量问题',
    amount: 2999,
    status: 'pending',
    createTime: '2023-11-28 10:00:00',
    records: [
      {
        time: '2023-11-28 10:00:00',
        content: '用户提交售后申请',
        operator: '张三',
        type: 'info'
      }
    ]
  }
])

// 方法
const getTypeTag = (type: string) => {
  const map: Record<string, string> = {
    refund: 'danger',
    exchange: 'warning',
    repair: 'info'
  }
  return map[type] || 'info'
}

const getTypeText = (type: string) => {
  const map: Record<string, string> = {
    refund: '退款',
    exchange: '换货',
    repair: '维修'
  }
  return map[type] || '未知类型'
}

const getStatusTag = (status: string) => {
  const map: Record<string, string> = {
    pending: 'warning',
    processing: 'primary',
    completed: 'success',
    rejected: 'info'
  }
  return map[status] || 'info'
}

const getStatusText = (status: string) => {
  const map: Record<string, string> = {
    pending: '待处理',
    processing: '处理中',
    completed: '已完成',
    rejected: '已拒绝'
  }
  return map[status] || '未知状态'
}

const handleSearch = () => {
  currentPage.value = 1
  loadData()
}

const resetSearch = () => {
  searchForm.value = {
    orderNo: '',
    type: '',
    status: '',
    dateRange: []
  }
  handleSearch()
}

const loadData = async () => {
  loading.value = true
  try {
    // 这里调用接口获取数据
    total.value = tableData.value.length
  } catch (error) {
    console.error('加载数据失败：', error)
  } finally {
    loading.value = false
  }
}

const handleDetail = (row: any) => {
  currentRecord.value = { ...row }
  drawerVisible.value = true
}

const handleProcess = (row: any) => {
  currentRecord.value = { ...row }
  dialogVisible.value = true
}

const submitProcess = async () => {
  if (!processFormRef.value) return
  
  await processFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        // 这里调用处理接口
        ElMessage.success('处理成功')
        dialogVisible.value = false
        drawerVisible.value = false
        loadData()
      } catch (error) {
        console.error('处理失败：', error)
      } finally {
        submitting.value = false
      }
    }
  })
}

const resetProcessForm = () => {
  if (processFormRef.value) {
    processFormRef.value.resetFields()
  }
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  loadData()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadData()
}

// 初始化
loadData()
</script>

<style scoped lang="scss">
.after-sale {
  .search-card {
    margin-bottom: 20px;
    
    .search-form {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      
      .el-form-item {
        margin-bottom: 0;
        margin-right: 0;
      }
    }
  }
  
  .list-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .amount {
      color: #f56c6c;
      font-weight: bold;
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .drawer-footer {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 16px;
    background-color: #fff;
    border-top: 1px solid #dcdfe6;
    text-align: right;
  }
  
  .operator {
    font-size: 12px;
    color: #909399;
    margin-top: 4px;
  }
}

// 响应式处理
@media screen and (max-width: 768px) {
  .after-sale {
    .search-form {
      .el-form-item {
        width: 100%;
      }
    }
  }
}
</style> 